package com.atguigu.gmallauth.controller;

import com.atguigu.gmallauth.service.AuthService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**编写授权接口，后台接收登录名和密码及登陆前的页面地址，
 * 登录成功后重定向到登陆前页面。return-url
 * @author Jia Fa
 * @create 2021-12-17 12:54
 */
@Controller
public class AuthController {

    @Autowired
    AuthService authService;


    @GetMapping("toLogin.html")
    public String toLogin(Model model, @RequestParam(value = "returnUrl",defaultValue = "http://www.gmall.com")String returnUrl){
        // 跳转至login页面,携带当前页面路径信息,用于登录成功后重定向  默认跳转到首页
        model.addAttribute("returnUrl",returnUrl);

        return "login";
    }

    @PostMapping("login")
    public String login(@RequestParam("loginName")String loginName,
                        @RequestParam("password")String password,
                        @RequestParam("returnUrl")String returnUrl,
                        HttpServletRequest request, HttpServletResponse response){

        // request 用来获取cookie
        this.authService.login(loginName,password,request,response);


        return "redirect:"+returnUrl;

    }
}
